<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Validator;

use Admin\Data\Common;
use Laminas\Validator\AbstractValidator;
use User\Entity\User;

class UserPhoneExistsValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const PHONE_EXISTS  = 'phoneExists';
    const INVALID       = 'phoneNumberInvalid';

    protected $entityManager;
    protected $userInfo;

    protected $messageTemplates = [
        self::NOT_SCALAR    => "这不是一个标准输入值",
        self::PHONE_EXISTS  => "该电话号码已经存在",
        self::INVALID       => "您的电话号码格式有误"
    ];

    public function __construct($options = null)
    {
        if(is_array($options)) {
            if(isset($options['entityManager']))    $this->entityManager = $options['entityManager'];
            if(isset($options['userInfo']))         $this->userInfo      = $options['userInfo'];
        }
        parent::__construct($options);
    }

    public function isValid($value, $context = null)
    {
        if (!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        $isValid = Common::checkPhoneNumber($value, $context['areaCode']);
        if(!$isValid) {
            $this->error(self::INVALID);
            return false;
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['areaCode' => $context['areaCode'], 'userPhone' => $value]);
        if($this->userInfo == null) {
            $isValid = ($user==null);
        } else {
            if($this->userInfo->getUserPhone() != $value && $user != null)
                $isValid = false;
            else
                $isValid = true;
        }
        if(!$isValid) $this->error(self::PHONE_EXISTS);

        return $isValid;
    }
}